package cn.bxshey.general.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;



@Slf4j
public class UploadTheFile {

    private static final String HTTP = "http://www.lyzhnb.top/"; //oss存储域名
    private static final String ACCESS_KEY = "QbGiNW7Hmi2BeXUaM86wfCQ_MXRYd3jYlQOo50Ga";  //七牛云的accessKey
    private static final String SECRET_KEY = "CVf6HvfIBLDFXIH3VCUMFG8FUpfP8XgQryWNMEah";   //七牛云的secretKey
    private static final String BUCKET = "lyzhnb-blog"; //仓库名
    private static final String DIRECTORY = "baby/"; //文件所在目录名

    /**
     * 上传图片文件  单个 或 多个
     */
    public List<String> uploadFile(MultipartFile[] file, List<String> key) {
//构造一个带指定 Region 对象的配置类 Region.region2() 意思是你的仓库是哪个地区的 例如 华南或华北等。。
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
//默认不指定key的情况下，以文件内容的hash值作为文件名
        List<String> path = new ArrayList<>();
        // 循环遍历的效果
        for (int i = 0; i < file.length; i++) {
            try {
                byte[] uploadBytes = file[i].getBytes();
                ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
                Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
                String upToken = auth.uploadToken(BUCKET);
                try {
                    Response response = uploadManager.put(byteInputStream, DIRECTORY + key.get(i), upToken, null, null);
                    //解析上传成功的结果
                    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                    path.add(HTTP + putRet.key);
                } catch (QiniuException ex) {
                    Response r = ex.response;
                    log.warn("{} 上传对象存储图片失败: {}", path, ex);
                }
            } catch (IOException ex) {
                //ignore 忽视
            }
        }
        return path; //返回路径交由前端
    }

    /**
     * 删除图片文件  单个 或 多个
     * pat 要删除的图片名
     */
    public Integer deleteFile(String[] path) {
        //构造一个带指定 Region 对象的配置类，指定七牛云的存储位置
        Configuration cfg = new Configuration(Region.region0());
        //设置密钥信息
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        int count = 0;
        try {
            //单次批量请求的文件数量不得超过1000
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            //添加要删除的文件名
            Arrays.stream(path).forEach(s -> batchOperations.addDeleteOp(BUCKET, DIRECTORY + s));
            //执行删除
            Response response = bucketManager.batch(batchOperations);
            BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
            for (int i = 0; i < path.length; i++) {
                BatchStatus status = batchStatusList[i];
                String key = path[i];
                //删除成功或失败提示信息
                if (status.code == 200) {
                    count++;
                } else {
                    log.warn("删除对象存储图片失败: {} -> {} ", status.data.error, key);
                }
            }
        } catch (QiniuException ex) {
            log.warn(ex.response.toString());
        }
        return count > 0 ? count : null;
    }

    /**
     * 检测上传文件类型
     *
     * @param file 文件
     * @return true 有效 false无效
     */
    public static boolean fileFormatCheck(MultipartFile[] file) {
        //文件超越20个则返回false
        if (file.length > 20)
            return false;
        String[] type = {"jpg", "png", "gif", "jpeg", "svg"};
        boolean mark = false;
        for (MultipartFile files : file) {
            //判断图片文件格式是否正确
            for (String str : type) {
                if (str.equalsIgnoreCase(StringUtils.substringAfterLast(files.getOriginalFilename(), "."))) {
                    mark = true;
                    break;
                }
                mark = false;
            }
            //如果有一个文件后缀名不对，则返回错误信息
            if (!mark) {
                return false;
            }
        }
        return true;
    }


    /**
     * 截取字符串
     *
     * @param path 字符串数组
     * @param dot  需要截取的字符，最后一次出现的位置开始截取
     * @return 字符串数组
     */
    public static String[] intercept(String[] path, String dot) {
        for (int i = 0; i < path.length; i++)
            if (path[i].contains(dot)) {
                path[i] = StringUtils.substringAfterLast(path[i], dot);
            }
        return path;
    }


}




